import smtplib
from email.mime.text import MIMEText
from email.header import Header
import requests

# ========== 1. 获取天气数据 ==========
def get_weather(city="Beijing"):
    # 使用免费的 API（和风天气、open-meteo 等，这里用 open-meteo）
    # url = f"https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074&current_weather=true"
    # response = requests.get(url)
    # data = response.json()
    # weather = data["current_weather"]
    # text = (
    #     f"城市: {city}\n"
    #     f"温度: {weather['temperature']}°C\n"
    #     f"风速: {weather['windspeed']} km/h\n"
    #     f"天气代码: {weather['weathercode']}\n"
    # )
    text = "zhuzhu"
    return text

# ========== 2. 发送邮件 ==========
def send_email(to_addr, subject, content):
    # 你的 QQ 邮箱账号
    from_addr = "3233473538@qq.com"
    # 你的 QQ邮箱SMTP授权码（不是密码，需要在QQ邮箱设置->账户里开通）
    password = "hvcjoasqynmibceg"

    # SMTP 服务器地址（QQ邮箱）
    smtp_server = "smtp.qq.com"

    # 构造邮件内容
    message = MIMEText(content, "plain", "utf-8")
    message["From"] = Header(from_addr)
    message["To"] = Header(to_addr)
    message["Subject"] = Header(subject, "utf-8")

    try:
        # 登录并发送
        server = smtplib.SMTP_SSL(smtp_server, 465)
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], message.as_string())
        server.quit()
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败:", e)

# ========== 3. 主程序 ==========
if __name__ == "__main__":
    weather_report = get_weather("北京")
    send_email("3233473538@qq.com", "今日天气预报", weather_report)